import * as mutationTypes from './mutation-type'

const mutations = {
  /**
   * 时钟管理详解：
   * inner：内部生效（需要清理）
   * keep: 一直保留
   */
  //添加时钟所应至全局
  [mutationTypes.ADD_INTERVAL](state,interval){
    switch(Object.prototype.toString.call(interval)){
      case '[object Array]':{
        state.intervals = [state.intervals,...interval];
      }break;
      case '[object Number]':{
        if(!state.intervals.find(v=>v.interval==interval)){
          state.intervals.push({
            interval:interval,
            type:'inner'
          })
        }
      }break;
      case '[object Object]':{
        if(!interval.hasOwnProperty("type")){
          interval.type = "inner"
        }
        if(!state.intervals.find(v=>v.interval==interval.interval)){
          state.intervals.push(interval)
        }
      }break;
    }
    // console.log(state.intervals)
  },
  //时钟清理
  [mutationTypes.CLEAR_INTERVALS](state,type){
    switch(Object.prototype.toString.call(type)){
      //清理条件
      case '[object Number]':{//按时钟
        state.intervals = state.intervals.filter(v=>{
          if(v.interval == type){
            window.clearInterval(v.interval)
          }else{
            return v
          }
        })
      }break;
      case '[object String]':{//按类型
        if(type=='all'){//全部
          state.intervals = state.intervals.filter(v=>{
            window.clearInterval(v.interval)
          })
        }else{
          state.intervals = state.intervals.filter(v=>{
            if(v.type == type){
              window.clearInterval(v.interval)
            }else{
              return v
            }
          })
        }
      }break;
      case '[object Object]':{//按额外条件清理(清理值相同)
        state.intervals = state.intervals.filter(v=>{
          for(let k in type){
            if(v.hasOwnProperty(k)&&type[k]==v[k]){
              window.clearInterval(v.interval)
            }else{
              return v
            }
          }
        })
      }break;
      case '[object Array]':{//清理组
        state.intervals = state.intervals.filter(v=>{
          for(let i=0;i<type.length;i++){
            if(v.type == type[i]){
              window.clearInterval(v.interval)
            }else{
              return v
            }
          }
        })
      }break;
      //默认清理inner
      default:{
        state.intervals = state.intervals.filter(v=>{
          if(v.type == 'inner'){
            window.clearInterval(v.interval)
          }else{
            return v
          }
        })
        // console.log("s.intervals",state.intervals)
      }
    }
  },
}

export default mutations